/**
 * Created by icyhy on 2017/5/25.
 */
"use strict";
var builder = require("../response/rest.result.builder");
var querystring = require('querystring');
var http = require("http");
var https = require('https');
var url = require("url");
var crypto = require("crypto");
var userModel = require("../models/user");
var nodeWeixinExpressSession = require('node-weixin-express-session');

function sha1(str){
  var md5sum = crypto.createHash("sha1");
  md5sum.update(str);
  str = md5sum.digest("hex");
  return str;
};

module.exports = {
  oAuth:function(req, res,next){
    var target = req.query.target || 'index';
    var url = global.we_client.getAuthorizeURL('http://' + global.domain + '/we/callback?target=' + target,'STATE','snsapi_userinfo');
    res.redirect(url)
  },

  /**
   * 认证授权后回调函数
   *
   * 根据openid判断是否用户已经存在
   * - 如果是新用户，注册并绑定，然后跳转到手机号验证界面
   * - 如果是老用户，跳转到主页
   */
  callBack:function(req, res, next){
    var target = req.query.target || 'index';
    console.log('target='+ target);
    console.log('----weixin callback -----')
    var code = req.query.code;
    global.we_client.getAccessToken(code, function (err, result) {
      console.dir(err)
      console.dir(result)
      if(!result.data){
        console.log('result.data undefined');
        return;
      }
      var accessToken = result.data.access_token;
      var openid = result.data.openid;

      console.log('token=' + accessToken);
      console.log('openid=' + openid);

      userModel.findByOpenid(openid, function(err, user){
        console.log('微信回调后，User.find_by_openid(openid) 返回的user = ' + user)
        if(err || user == null){
          console.log('user is not exist.')
          global.we_client.getUser(openid, function (err, result) {
            console.log('use weixin api get user: '+ err)
            console.log(result)
            var oauth_user = result;
            var _user = new userModel();
            _user.openid = oauth_user.openid;
            _user.nickname = oauth_user.nickname;
            _user.sex = oauth_user.sex;
            _user.city = oauth_user.city;
            _user.province = oauth_user.province;
            _user.country = oauth_user.country
            _user.headimgurl = oauth_user.headimgurl;
            _user.save(function(err, newuser) {
              if (err) {
                console.log('User save error ....' + err);
              } else {
                console.log('User save sucess ....' + err);
                nodeWeixinExpressSession.set(req, 'current_open_id', _user.openid, function(){
                  console.log('session save openid: ' + _user.openid);
                });
                var userid = newuser.id;
                res.redirect('/' + target + ".html#/?userid=" + userid);
              }
            });

          });
        }else{
          console.log('根据openid查询，用户已经存在')
          nodeWeixinExpressSession.set(req, 'current_open_id', user.openid, function(){
            console.log('session save openid: ' + user.openid);
          });
          var userid = user.id;
          res.redirect('/' + target + ".html#/?userid=" + userid);
        }
      });
    });
  },

  validateToken: function (req, res, next) {
    var query = url.parse(req.url,true).query;
    //console.log("*** URL:" + req.url);
    //console.log(query);
    var signature = query.signature;
    var echostr = query.echostr;
    var timestamp = query['timestamp'];
    var nonce = query.nonce;
    var oriArray = new Array();
    oriArray[0] = nonce;
    oriArray[1] = timestamp;
    oriArray[2] = 'rainbow'; //这里是你在微信开发者中心页面里填的token
    oriArray.sort();
    var original = oriArray.join('');
    console.log("Original str : " + original);
    console.log("Signature : " + signature );
    var scyptoString = sha1(original);
    if(signature == scyptoString){
      res.end(echostr);
      console.log("Confirm and send echo back");
    }else {
      res.end("false");
      console.log("Failed!");
    }
  },
  /**
   * 更新公众号自定义菜单
   */
  updateMenu:function(req, res, next){
    var post_data = querystring.stringify( {
      "button": [
        {
          "type": "view",
          "name": "加入部落",
          "url": "http://rainbow2017.tunnel.qydev.com/we/oauth?target=index"
        },
        {
          "type": "view",
          "name": "部落打卡",
          "url": "http://rainbow2017.tunnel.qydev.com/we/oauth?target=submitdoc"
        },
        {
          "name": "我",
          "sub_button": [
            {
              "type": "view",
              "name": "排行榜",
              "url": "http://rainbow2017.tunnel.qydev.com/we/oauth?target=ranking"
            },
            {
              "type": "view",
              "name": "审核打卡",
              "url": "http://rainbow2017.tunnel.qydev.com/we/oauth?target=check"
            },
            {
              "type": "view",
              "name": "个人中心",
              "url": "http://rainbow2017.tunnel.qydev.com/we/oauth?target=usercenter"
            }
          ]
        }
      ]
    });


    var options = {
      hostname: 'api.weixin.qq.com',
      path: '/cgi-bin/menu/create?access_token=' + global.accesstoken,
      method: 'POST',
    };
    var req = https.request(options, function (res) {
      res.setEncoding('utf8');
      //console.log("statusCode: ", res.statusCode);
      //console.log("headers: ", res.headers);
      var bodyChunks = '';
      res.on('data', function (chunk) {
        bodyChunks += chunk;
      }).on('end', function () {
        var body = JSON.parse(bodyChunks);
        console.dir(body);
      })
    });

    req.on('error', function (e) {
      console.log('ERROR: ' + e.message);
    });

    req.write(post_data);
    req.end();
  }
}
